<template>
  <div class="event-template-panel">
    <a-card title="事件模板管理" :bordered="false">
      <template #extra>
        <a-space>
          <a-button type="primary" @click="showCreateModal">
            <template #icon>
              <IconifyIcon icon="ant-design:plus-outlined" />
            </template>
            新建模板
          </a-button>
          <a-button @click="refreshData">
            <template #icon>
              <IconifyIcon icon="ant-design:reload-outlined" />
            </template>
            刷新
          </a-button>
        </a-space>
      </template>

      <a-table
        :columns="columns"
        :data-source="templates"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'templateType'">
            <a-tag :color="getTemplateTypeColor(record.templateType)">
              {{ getTemplateTypeLabel(record.templateType) }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusLabel(record.status) }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'actions'">
            <a-space>
              <a-button type="link" size="small" @click="showEditModal(record)">
                编辑
              </a-button>
              <a-button type="link" size="small" @click="handleUse(record)">
                使用
              </a-button>
              <a-popconfirm
                title="确定要删除这个模板吗？"
                @confirm="handleDelete(record.id)"
              >
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 创建/编辑模板模态框 -->
    <a-modal
      :open="modalVisible"
      :title="editingTemplate ? '编辑事件模板' : '新建事件模板'"
      width="800px"
      @ok="handleSave"
      @cancel="closeModal"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="模板名称" name="name">
              <a-input
                v-model:value="formData.name"
                placeholder="请输入模板名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="模板类型" name="templateType">
              <a-select
                v-model:value="formData.templateType"
                placeholder="请选择模板类型"
              >
                <a-select-option value="ALERT">告警模板</a-select-option>
                <a-select-option value="NOTIFICATION">通知模板</a-select-option>
                <a-select-option value="LOG">日志模板</a-select-option>
                <a-select-option value="CUSTOM">自定义模板</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="模板内容" name="content">
          <a-textarea
            v-model:value="formData.content"
            placeholder="请输入模板内容"
            :rows="6"
          />
        </a-form-item>

        <a-form-item label="模板描述" name="description">
          <a-textarea
            v-model:value="formData.description"
            placeholder="请输入模板描述"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';
import type { FormInstance } from 'ant-design-vue';

// Props
interface Props {
  resourceId: string;
  resourceType: string;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  'template-created': [template: any];
  'template-updated': [template: any];
}>();

// 响应式数据
const loading = ref(false);
const modalVisible = ref(false);
const editingTemplate = ref<any>(null);
const formRef = ref<FormInstance>();

// 表单数据
const formData = reactive({
  name: '',
  templateType: '',
  content: '',
  description: '',
});

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入模板名称' }],
  templateType: [{ required: true, message: '请选择模板类型' }],
  content: [{ required: true, message: '请输入模板内容' }],
};

// 模拟数据
const templates = ref([
  {
    id: '1',
    name: '资源创建通知模板',
    templateType: 'NOTIFICATION',
    content: '资源 {{resource.name}} 已成功创建，ID: {{resource.id}}',
    description: '用于资源创建成功后的通知',
    status: 'ACTIVE',
  },
  {
    id: '2',
    name: '系统告警模板',
    templateType: 'ALERT',
    content: '系统告警: {{alert.message}}，级别: {{alert.level}}',
    description: '用于系统告警事件',
    status: 'ACTIVE',
  },
  {
    id: '3',
    name: '操作日志模板',
    templateType: 'LOG',
    content: '用户 {{user.name}} 执行了 {{action}} 操作',
    description: '用于记录用户操作日志',
    status: 'ACTIVE',
  },
]);

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 表格列配置
const columns = [
  {
    title: '模板名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '模板类型',
    dataIndex: 'templateType',
    key: 'templateType',
    width: 120,
  },
  {
    title: '模板内容',
    dataIndex: 'content',
    key: 'content',
    ellipsis: true,
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    fixed: 'right',
  },
];

// 方法
const loadData = () => {
  loading.value = true;
  setTimeout(() => {
    pagination.value.total = templates.value.length;
    loading.value = false;
  }, 500);
};

const refreshData = () => {
  loadData();
  message.success('数据刷新成功');
};

const showCreateModal = () => {
  editingTemplate.value = null;
  resetFormData();
  modalVisible.value = true;
};

const showEditModal = (record: any) => {
  editingTemplate.value = record;
  Object.assign(formData, record);
  modalVisible.value = true;
};

const closeModal = () => {
  modalVisible.value = false;
  resetFormData();
};

const resetFormData = () => {
  Object.assign(formData, {
    name: '',
    templateType: '',
    content: '',
    description: '',
  });
  formRef.value?.clearValidate();
};

const handleSave = async () => {
  try {
    await formRef.value?.validate();

    if (editingTemplate.value) {
      const index = templates.value.findIndex(
        (item) => item.id === editingTemplate.value.id,
      );
      if (index !== -1) {
        templates.value[index] = {
          ...editingTemplate.value,
          ...formData,
        };
      }
      message.success('事件模板更新成功');
      emit('template-updated', formData);
    } else {
      const newTemplate = {
        id: Date.now().toString(),
        ...formData,
        status: 'ACTIVE',
      };
      templates.value.unshift(newTemplate);
      message.success('事件模板创建成功');
      emit('template-created', newTemplate);
    }

    closeModal();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleDelete = (id: string) => {
  const index = templates.value.findIndex((item) => item.id === id);
  if (index !== -1) {
    templates.value.splice(index, 1);
    message.success('事件模板删除成功');
  }
};

const handleUse = (record: any) => {
  message.success(`模板 ${record.name} 使用功能开发中...`);
};

const getTemplateTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    ALERT: '告警模板',
    NOTIFICATION: '通知模板',
    LOG: '日志模板',
    CUSTOM: '自定义模板',
  };
  return typeMap[type] || type;
};

const getTemplateTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    ALERT: 'red',
    NOTIFICATION: 'blue',
    LOG: 'green',
    CUSTOM: 'purple',
  };
  return colorMap[type] || 'default';
};

const getStatusLabel = (status: string) => {
  const statusMap: Record<string, string> = {
    ACTIVE: '活跃',
    INACTIVE: '非活跃',
  };
  return statusMap[status] || status;
};

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    ACTIVE: 'green',
    INACTIVE: 'default',
  };
  return colorMap[status] || 'default';
};

// 生命周期
onMounted(() => {
  loadData();
});
</script>

<style lang="less" scoped>
.event-template-panel {
  // 样式可以根据需要添加
}
</style>
